var express = require('express');
var app = module.exports = express();

var logger = require('morgan');
app.use(logger('dev'));

var multer = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'upload');
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now());
    }
})
var upload = multer({ storage: storage });

var server = app.listen(8000, '192.168.1.115', function() {
	var host = server.address().address;
	var port = server.address().port;
	console.log('Express API listening at http://%s:%s', host, port);
});

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1');
    if(req.method == "OPTIONS") {
        res.sendStatus(200);/*让options请求快速返回*/
    } else {
        next();
    }
});

//mount local api
require('./api.js')(app);

//proxy remote api
var proxyMiddleware = require('http-proxy-middleware');
var proxy_target = {
    "sev": "http://20150915.team-lab.cn",
    "dev": "http://20150915.team-lab.cn",
    "stg": "http://api.stg-darwin.lofter.com"
};
proxy_target = proxy_target[process.env.NODE_ENV];
var proxy = proxyMiddleware('/api', {
    changeOrigin: true,
    target: proxy_target
});
app.use(proxy);


